package com.ghck.server.controller;

import java.security.Principal;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.ghck.server.controller.access.ArgIndexForPrintLog;
import com.ghck.server.model.TestAnswer;
import com.ghck.server.model.TestCategoryDict;
import com.ghck.server.model.request.QuestionReq;
import com.ghck.server.model.response.ResultList;
import com.ghck.server.model.response.ResultObject;
import com.ghck.server.model.response.TestAnswerRes;
import com.ghck.server.model.response.TestCategoryDictRes;
import com.ghck.server.service.TestAnswerService;
import com.ghck.server.service.TestCategoryDictService;
import com.ghck.server.service.TestQuestionService;

@RequestMapping("/questionnaire")
@RestController
public class QuestionnaireController {
	
	private static Logger logger = LoggerFactory.getLogger(QuestionnaireController.class);
	
	@Autowired
	TestCategoryDictService testCategoryDictService;//健康自测类型
	
	@Autowired
	TestQuestionService testQuestionService;//测试题
	
	@Autowired
	TestAnswerService testAnswerService;//测试记录
	
	/**
	 * 加载试卷列表，
	 * @param parentId
	 * @param start
	 * @param limit ： 0表示加载所有
	 * @return
	 */
	@ArgIndexForPrintLog(indexes={0,1,2})
	@RequestMapping(value = "/fetch_paper_list/{parentId}", method = RequestMethod.GET)
	public ResultList<TestCategoryDict> fetchPaperList(
			@PathVariable("parentId") Integer parentId,
			Integer start,
			Integer limit,Principal principal){
		
		List<TestCategoryDict> list = testCategoryDictService.findByParentId(parentId, start, limit);
		
		
		return new ResultList<>(list);
	}
	
	/**
	 * 加载一个试卷的题目
	 * @param parentId
	 * @return
	 */
	@ArgIndexForPrintLog(indexes={0})
	@RequestMapping(value = "/fetch_paper/{paperId}", method = RequestMethod.GET)
	public ResultObject<TestCategoryDictRes> fetchPaper(@PathVariable("paperId") Integer paperId,Principal principal){
		
		TestCategoryDictRes res = testCategoryDictService.findPaperByIdWithCahche(paperId);
		
		return new ResultObject<TestCategoryDictRes>(res);
	}
	
	/**
	 * [
	 * 	{
	 * 		questionId:12,
	 * 		itemIds:[1,2,3]
	 *  }
	 * ]
	 * @param paperId
	 * @param principal
	 * @return
	 */
	@ArgIndexForPrintLog(indexes={0,1})
	@RequestMapping(value = "/patients/submit_paper/{paperId}", method = RequestMethod.POST,consumes = "application/json;chatset=UTF-8")
	public ResultObject<TestAnswer> submitPaper(@PathVariable("paperId") Integer paperId,@RequestBody QuestionReq question ,Principal principal){
		
		Integer userId = question.getUserId();
		if(null != principal){
			userId = Integer.parseInt(principal.getName());
		}
		TestAnswer res = testAnswerService.submitPaper(userId,paperId,question.getStationId(),question);
		return new ResultObject<TestAnswer>(res);
	}
	
	
	/**
	 * 获取我的答案
	 * @param parentId
	 * @return
	 */
	@ArgIndexForPrintLog(indexes={0})
	@RequestMapping(value = "/patients/fetch_answer_list/{parentId}", method = RequestMethod.GET)
	public ResultList<TestAnswerRes> fetchTestAnswer(
			@PathVariable("parentId") Integer parentId,
			Integer start,
			Integer limit,Principal principal){
		
		Integer userId = Integer.parseInt(principal.getName());
		
		List<TestAnswerRes> res = testAnswerService.findAnswer(userId,parentId,start,limit);
		
		return new ResultList<TestAnswerRes>(res);
	}
	
	
//	//======================管理平台====================
//	//添加试卷
//	
//	@ArgIndexForPrintLog(indexes={0})
//	@RequestMapping(value = "/paper/add/{categoryId}", method = RequestMethod.POST)
//	public ResultObject<Integer> addPaper(@RequestBody PaperReq req,@PathVariable("categoryId") Integer categoryId){
//		//校验
//		if(IntegerUtil.isNotPositiveInteger(categoryId)){
//			GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"请指定试卷分类");
//			logger.info("添加试卷失败",exception);
//			throw exception;
//		}
//		TestCategoryDict parent = testCategoryDictService.findTestCategoryDictById(categoryId);
//		if(parent==null){
//			GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"试卷分类不存在");
//			logger.info("添加试卷失败",exception);
//			throw exception;
//		}
//		req.setParentId(categoryId);
//		
//		req.setScore(0); //分数清零
//		//非空校验
//		List<QuestionReq> questionReqs = req.getQuestions();
//		if (CollectionUtils.isNotEmpty(questionReqs)) {
//			for (QuestionReq questionReq : questionReqs) {
//				questionReq.setParent(req);
//				questionReq.setScore(0); //分数清零
//				if(StringUtils.isEmpty(questionReq.getDescription())){
//					GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"试题描述不能为空");
//					logger.info("添加试卷失败",exception);
//					throw exception;
//				}
//				List<TestQuestionItemReq> items = questionReq.getItems();
//				if (CollectionUtils.isNotEmpty(items)) {
//					for (TestQuestionItemReq testQuestionItem : items) {
//						testQuestionItem.setParent(questionReq);
//						if(StringUtils.isEmpty(testQuestionItem.getDescription())){
//							GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"试题【"+questionReq.getDescription()+"】的选项不能为空");
//							logger.info("添加试卷失败",exception);
//							throw exception;
//						}
//						if(testQuestionItem.getScore()==null){
//							GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"试题选项【"+testQuestionItem.getDescription()+"】分数不能为空");
//							logger.info("添加试卷失败",exception);
//							throw exception;
//						}
//						if(questionReq.getScore()==null){
//							questionReq.setScore(0);
//						}
//						questionReq.setScore(questionReq.getScore()+testQuestionItem.getScore());
//					}
//					
//					if(questionReq.getScore()==0){
//						GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"试题【"+questionReq.getDescription()+"】的选项分数之和等于0");
//						logger.info("添加试卷失败",exception);
//						throw exception;
//					}
//				}else{
//					GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"试题【"+questionReq.getDescription()+"】没有选项");
//					logger.info("添加试卷失败",exception);
//					throw exception;
//				}
//				if(req.getScore()==null){
//					req.setScore(0);
//				}
//				req.setScore(req.getScore()+questionReq.getScore());
//			}
//		}else{
//			GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"试卷的试题不能为空");
//			logger.info("添加试卷失败",exception);
//			throw exception;
//		}
//		
//		Integer id = testAnswerService.addParer(req);
//		
//		testCategoryDictService.syncSingletonRedis(id);
//		
//		return new ResultObject<Integer>(id);
//	}
//	
//	@ArgIndexForPrintLog(indexes={0})
//	@RequestMapping(value = "/paper/modify/{paperId}", method = RequestMethod.PUT)
//	public ResultObject<Integer> modifyPaper(@RequestBody PaperReq req,@PathVariable("paperId") Integer paperId){
//		//校验
//		if(IntegerUtil.isNotPositiveInteger(paperId)){
//			GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"请指定试卷ID");
//			logger.info("修改试卷失败",exception);
//			throw exception;
//		}
//		
//		TestCategoryDict parent = testCategoryDictService.findTestCategoryDictById(paperId);
//		if(parent==null){
//			GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"试卷不存在");
//			logger.info("添加试卷失败",exception);
//			throw exception;
//		}
//		req.setScore(0); //分数清零
//		//非空校验
//		List<QuestionReq> questionReqs = req.getQuestions();
//		if (CollectionUtils.isNotEmpty(questionReqs)) {
//			for (QuestionReq questionReq : questionReqs) {
//				questionReq.setParent(req);
//				questionReq.setScore(0); //分数清零
//				if(StringUtils.isEmpty(questionReq.getDescription())){
//					GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"试题描述不能为空");
//					logger.info("添加试卷失败",exception);
//					throw exception;
//				}
//				List<TestQuestionItemReq> items = questionReq.getItems();
//				if (CollectionUtils.isNotEmpty(items)) {
//					for (TestQuestionItemReq testQuestionItem : items) {
//						testQuestionItem.setParent(questionReq);
//						if(StringUtils.isEmpty(testQuestionItem.getDescription())){
//							GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"试题【"+questionReq.getDescription()+"】的选项不能为空");
//							logger.info("添加试卷失败",exception);
//							throw exception;
//						}
//						if(testQuestionItem.getScore()==null){
//							GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"试题选项【"+testQuestionItem.getDescription()+"】分数不能为空");
//							logger.info("添加试卷失败",exception);
//							throw exception;
//						}
//						if(questionReq.getScore()==null){
//							questionReq.setScore(0);
//						}
//						if(IntegerUtil.isPositiveInteger(testQuestionItem.getInUsed())){
//							questionReq.setScore(questionReq.getScore()+testQuestionItem.getScore());
//						}
//					}
//					
//					if(questionReq.getScore()==0){
//						GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"试题【"+questionReq.getDescription()+"】的选项分数之和等于0");
//						logger.info("添加试卷失败",exception);
//						throw exception;
//					}
//				}else{
//					GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"试题【"+questionReq.getDescription()+"】没有选项");
//					logger.info("添加试卷失败",exception);
//					throw exception;
//				}
//				if(req.getScore()==null){
//					req.setScore(0);
//				}
//				if(IntegerUtil.isPositiveInteger(questionReq.getInUsed())){
//					req.setScore(req.getScore()+questionReq.getScore());
//				}
//			}
//		}else{
//			GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"试卷的试题不能为空");
//			logger.info("添加试卷失败",exception);
//			throw exception;
//		}
//		
//		Integer id = testAnswerService.modifyParer(req);
//		testCategoryDictService.syncSingletonRedis(id);
//		return new ResultObject<Integer>(id);
//	}
//	
//	@ArgIndexForPrintLog(indexes={0})
//	@RequestMapping(value = "/fetch_answer_list",method = RequestMethod.GET)
//	public ResultList<TestAnswerRes> queryTestAnswer(TestAnswerQuery query){
//		ResultList<TestAnswerRes> resultList = new ResultList<>();
//		List<TestAnswerRes> result = testAnswerService.findTestAnswerByQuery(query);
//		Integer count  = testAnswerService.countTestAnswerByQuery(query);
//		query.setCount(count);
//		resultList.setExt(query);
//		resultList.setItemList(result);
//		
//		return resultList;
//	}
//	
//	
//	@ArgIndexForPrintLog(indexes={0})
//	@RequestMapping(value = "/answer/modify/{paperId}",method = RequestMethod.PUT)
//	public ResultObject<Integer> modifyAnswer( @RequestBody TestAnswer testAnswer,@PathVariable("paperId") Integer paperId){
//		testAnswer.setId(paperId);
//		testAnswerService.updateTestAnswer(testAnswer);
//		return new ResultObject<>(paperId);
//	}
}
